package cn.edu.sdjzu.xg2103.dao;

import cn.edu.sdjzu.xg2103.controller.helper.JdbcHelper;
import cn.edu.sdjzu.xg2103.entity.Department;
import cn.edu.sdjzu.xg2103.entity.School;
import cn.edu.sdjzu.xg2103.exception.BysjException;
import cn.edu.sdjzu.xg2103.service.SchoolService;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DepartmentDao {
    private static DepartmentDao departmentDao = null;
    //将唯一构造器设置成私有，阻止在本类外生成本类的对象
    public static DepartmentDao getInstance(){
        //静态变量SchoolDao为null时，才创建SchoolDao对象
        //第二次或后来调用本方法就不指向null了，就不在创建对象。
        if (departmentDao == null){
            departmentDao = new DepartmentDao();
        }
        return departmentDao;
    }
    public Department find(int id)throws SQLException {
        //创建School类型的引用，暂时不创建对象
        Department desiredU = null;
        //获得数据库的连接
        Connection connection = JdbcHelper.getConn();
        String sql_select_id = "select * from department where id=?";
        PreparedStatement pstmt_select_id = connection.prepareStatement(sql_select_id);
        pstmt_select_id.setInt(1,id);
        ResultSet resultSet_select_id = pstmt_select_id.executeQuery();
        //如果表中存在id对应的元组，则获得表中的字段值，并创建对象
        if (resultSet_select_id.next()){
            String description = resultSet_select_id.getString("description");
            String no = resultSet_select_id.getString("no");
            String remarks = resultSet_select_id.getString("remarks");
            int school_id = resultSet_select_id.getInt("school_id");
            School school = SchoolService.getInstance().find(school_id);
            desiredU = new Department(id,description,no,remarks,school);
        }
        //关闭三个资源
        JdbcHelper.close(resultSet_select_id,pstmt_select_id,connection);
        return desiredU;
    }
    public boolean update (Connection connection,Department department) throws SQLException, BysjException {
        String sql_update = "update department" + "set name = ? where id =1";
        PreparedStatement pstmt_insert = connection.prepareStatement(sql_update);
        pstmt_insert.setString(1,department.getDescription());
        //执行预编译语句，影响的行数保存在rowAffected中
        int rowAffected = pstmt_insert.executeUpdate();
        return rowAffected > 0;
    }

}
